package com.healthguide.backend.controller;

import com.healthguide.backend.entity.MenstrualCycle;
import com.healthguide.backend.repository.MenstrualCycleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api/menstrual-cycles")
@CrossOrigin(origins = "*")
public class MenstrualCycleController {
    
    @Autowired
    private MenstrualCycleRepository menstrualCycleRepository;
    
    @GetMapping("/user/{userId}")
    public List<MenstrualCycle> getUserMenstrualCycles(@PathVariable Long userId) {
        return menstrualCycleRepository.findByUserIdOrderByStartDateDesc(userId);
    }
    
    @GetMapping("/user/{userId}/next")
    public ResponseEntity<LocalDate> getNextPeriodDate(@PathVariable Long userId) {
        List<MenstrualCycle> cycles = menstrualCycleRepository.findByUserIdOrderByStartDateDesc(userId);
        if (cycles.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        
        MenstrualCycle lastCycle = cycles.get(0);
        LocalDate nextPeriod = lastCycle.getStartDate().plusDays(lastCycle.getCycleLength());
        return ResponseEntity.ok(nextPeriod);
    }
    
    @PostMapping
    public MenstrualCycle createMenstrualCycle(@RequestBody MenstrualCycle menstrualCycle) {
        return menstrualCycleRepository.save(menstrualCycle);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<MenstrualCycle> updateMenstrualCycle(
            @PathVariable Long id,
            @RequestBody MenstrualCycle cycleDetails) {
        return menstrualCycleRepository.findById(id)
                .map(cycle -> {
                    cycle.setStartDate(cycleDetails.getStartDate());
                    cycle.setEndDate(cycleDetails.getEndDate());
                    cycle.setCycleLength(cycleDetails.getCycleLength());
                    cycle.setPeriodLength(cycleDetails.getPeriodLength());
                    cycle.setSymptoms(cycleDetails.getSymptoms());
                    cycle.setMood(cycleDetails.getMood());
                    return ResponseEntity.ok(menstrualCycleRepository.save(cycle));
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteMenstrualCycle(@PathVariable Long id) {
        return menstrualCycleRepository.findById(id)
                .map(cycle -> {
                    menstrualCycleRepository.delete(cycle);
                    return ResponseEntity.ok().build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
}
